﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GDIExtension;

namespace Patchworker
{
	public partial class MainWindow : Form
	{
		private void TileList_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Delete)
			{
				ConfigContainer.Instance.suspendRefresh();

					while (TileList.SelectedItems.Count > 0)
					{
						ImageListItem currentItem = (ImageListItem)TileList.SelectedItems[0];

						ConfigContainer.Instance.RemoveTile(currentItem.ImageReference);

						TileList.Items.Remove(currentItem);
					}
					ConfigContainer.Instance.resumeRefresh(false);

					if (ConfigContainer.Instance.NumFullFrames==0)
					{
						//when delete all, initialize
						initializeForms();
					}
			}
		}

		private void ImageUpButton_Click(object sender, EventArgs e)
		{
			if (TileList.SelectedIndex != -1)
			{
				if (TileList.SelectedIndex > 0)
				{
					int selectedIndex = TileList.SelectedIndex;
					swapTiles(TileList.SelectedIndex, TileList.SelectedIndex - 1);

					TileList.SelectedIndices.Clear();
					TileList.SelectedIndex = selectedIndex - 1;
				}
			}
		}

		private void ImageDownButton_Click(object sender, EventArgs e)
		{
			if (TileList.SelectedIndex != -1)
			{
				if (TileList.SelectedIndex < TileList.Items.Count - 1)
				{
					int selectedIndex = TileList.SelectedIndex;

					swapTiles(TileList.SelectedIndex, TileList.SelectedIndex + 1);

					TileList.SelectedIndices.Clear();
					TileList.SelectedIndex = selectedIndex + 1;
				}
			}
		}

		private void swapTiles(int aIndex, int bIndex)
		{
			swapTiles((ImageListItem)TileList.Items[aIndex], (ImageListItem)TileList.Items[bIndex]);
		}

		private void swapTiles(ImageListItem a, ImageListItem b)
		{
			int aIndex = TileList.Items.IndexOf(a);
			int bIndex = TileList.Items.IndexOf(b);

			if (aIndex != bIndex && aIndex != -1 && bIndex != -1)
			{
				TileList.Items[aIndex] = b;
				TileList.Items[bIndex] = a;

				TileList.Refresh();

				ConfigContainer.Instance.swapImageTiles(aIndex, bIndex);
			}
		}
	}
}
